package cc.telecomdigital.tdstock.trading.Services;

import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;

import cc.telecomdigital.tdstock.R;
import cc.telecomdigital.tdstock.Framework.UniqueItem.DeviceInfo;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;
import cc.telecomdigital.tdstock.Services.SoapTransport;
import cc.telecomdigital.tdstock.trading.Common.Trade_AppConstant;

import android.content.Context;
import android.os.Handler;
import android.os.Message;

public class TradeChangePassword
{
	private final String	LOG_TAG	= "TradeChangePassword";

	// Call back interface
	public interface ITradeChangePasswordResponse
	{
		// if iSuccessfulSend == false, it means the there is a communication
		// error
		// do not consider the iReponse as valid response;
		void ResponseFunc(boolean iSuccessfulSend,
				TradeChangePasswordResult iResponse);
	}

	public class TradeChangePasswordResult
	{
		public boolean	Result;
		public String	StatusCode;
		public String	BrokerMessage;
		public String	UsrMessage;

		public TradeChangePasswordResult(boolean iResult, String iStatusCode,
				String iBrokerMessage, String iUserMessage)
		{
			Result = iResult;
			StatusCode = iStatusCode;
			BrokerMessage = iBrokerMessage;
			UsrMessage = iUserMessage;
		}
	}

	private final boolean debugMode = false;
	private Context	callerContext;
	private SoapObject	soapRequest;
	private boolean	demoData	= false;
	private Handler	messageHandler;

	public TradeChangePassword(Context iContext)
	{
		callerContext = iContext;
		soapRequest = new SoapObject(TradeAppInfo.NAMESPACE, "ChangePassword");
		soapRequest.addProperty("DeviceID",
				TradeAppInfo.GetDeviceID(iContext));
		soapRequest.addProperty("UIN", TradeAppInfo.GetUIN());
		soapRequest.addProperty("ProtocolVer",
				TradeAppInfo.GetProtocolVersion());
		soapRequest.addProperty("BrokerID", TradeAppInfo.BrokerID);
		soapRequest.addProperty("Language", DeviceInfo.GetLanguageString());
	}
	
	public void Dispose()
	{		
		messageHandler = null;
		if (debugMode)
			TDStockLog.i(LOG_TAG, "We have no reference anymore");	
	}
	

	public void SetUserInformation(String iUser, String iOldPassword,
			String iNewPassword)
	{
		soapRequest.addProperty("ClientID", iUser);
		soapRequest.addProperty("ClientOldPassword", iOldPassword);
		soapRequest.addProperty("ClientNewPassword", iNewPassword);
	}

	private ITradeChangePasswordResponse	responseHandler;

	// If we are running a demo version, the iUseDemoData could be a fake send
	public void SendRequest(boolean iUseDemoData,
			ITradeChangePasswordResponse iTradingChangePasswordResponse)
	{
		demoData = iUseDemoData;
		responseHandler = iTradingChangePasswordResponse;
		messageHandler = new Handler()
		{
			@Override
			public void handleMessage(Message msg)
			{
				if (responseHandler == null)
					return;

				switch (msg.what)
				{
					case REQUEST_DATA_SENT_FAIL:
						responseHandler.ResponseFunc(false, null);
						break;

					case REQUEST_DATA_SENT_SUCCESS:
						responseHandler.ResponseFunc(true,
								(TradeChangePasswordResult) msg.obj);
						break;
				}
			}
		};
		// Start the Thread
		Thread internalThreadObj = new Thread()
		{
			@Override
			public void run()
			{
				Message msg;
				TradeChangePasswordResult infoData;

				// Provide success or fail reply
				msg = new Message();
				infoData = SendData(demoData);
				if ((infoData.Result == false) || (infoData.StatusCode == null)
						|| (infoData.StatusCode.length() == 0))
					msg.what = REQUEST_DATA_SENT_FAIL;
				else
				{
					msg.what = REQUEST_DATA_SENT_SUCCESS;
					msg.obj = infoData;
				}
				messageHandler.sendMessage(msg);
			}			
		};
		internalThreadObj.setName(LOG_TAG);
		internalThreadObj.start();
	}

	private final int	REQUEST_DATA_SENT_FAIL		= 0;
	private final int	REQUEST_DATA_SENT_SUCCESS	= 1;
	private TradeChangePasswordResult SendData(boolean iUseDemoData)
	{
		//Prevent for multiple call for network
		synchronized(TradeAppInfo.padLock)
		{
			TradeChangePasswordResult resultCode;
			SoapSerializationEnvelope envelope;
			String usrMsg;
			String statusCode;
			String brokerMsg;
			boolean hasSent;
			
			// String services;
			// String deviceID;
			if (iUseDemoData == true)
			{
				try
				{
					Thread.sleep(Trade_AppConstant.demoHoldTime);
				}
				catch (InterruptedException e)
				{
					e.printStackTrace();
					TDStockLog.e(LOG_TAG, "SendData=>Exception: " + e.toString());
				}
				
				if (debugMode)
					TDStockLog.i(LOG_TAG, "Using Prepared Data");
				resultCode = new TradeChangePasswordResult(true, "3", null, null);
				return resultCode;
			}

			hasSent = false;
			if (DeviceInfo.IsNetworkAvailable(callerContext) == false)
			{
				resultCode = new TradeChangePasswordResult(hasSent, null, null,
						null);
				return resultCode;
			}
	
			envelope = new SoapSerializationEnvelope(TradeAppInfo.SOAP_VERSION);
	
			soapRequest.addProperty("SeqNo", TradeAppInfo.GetSeqNo(true));
			// Last modification of the time
			soapRequest.addProperty(
					"Timestamp",
					TradeAppInfo.GetCurrentTimeStamp() + ","
							+ TradeAppInfo.GetSessionToken());
			envelope.setOutputSoapObject(soapRequest);
	
			// deviceID = null;
			// services = null;
			statusCode = null;
			usrMsg = null;
			brokerMsg = null;
	
			try
			{
				SoapObject resultsRequestSOAP;
				SoapObject soapResults;
	
				SoapTransport dataTransfer;
				
				if (TradeAppInfo.useSSLSetting)
					dataTransfer = new SoapTransport( callerContext, TradeAppInfo.GetURLAddress(true),
					 							TradeAppInfo.SOAP_COMMUNIC_Timeout, R.raw.ca_stock);
				else
					dataTransfer = new SoapTransport( callerContext, TradeAppInfo.GetURLAddress(false), 
												TradeAppInfo.SOAP_COMMUNIC_Timeout);
				
				if (debugMode)
					TDStockLog.i(LOG_TAG, "Try sending Data");
				
				dataTransfer.SendData(TradeAppInfo.SOAP_SERVICENAME, envelope);
						
				resultsRequestSOAP = (SoapObject) envelope.bodyIn;
				if (debugMode)
					TDStockLog.i(LOG_TAG, "Parsing Data");
				
				hasSent = true;
				soapResults = (SoapObject) resultsRequestSOAP
						.getProperty("ChangePasswordResult");
	
				statusCode = TradeAppInfo.GetSoapProperty(soapResults, LOG_TAG,
						"StatusCode");
				brokerMsg = TradeAppInfo.GetSoapProperty(soapResults, LOG_TAG,
						"BrokerMessage");
				// deviceID = TradeAppInfo.GetSoapProperty(soapResults, LOG_TAG,
				// "DeviceID");
				// services = TradeAppInfo.GetSoapProperty(soapResults, LOG_TAG,
				// "Services");
			}
			catch (java.net.SocketTimeoutException e)
			{
				e.printStackTrace();
				TDStockLog.e(LOG_TAG, "Timeout: " + e.toString());
			}
			catch (Exception e)
			{
				e.printStackTrace();
				TDStockLog.e(LOG_TAG, e.toString());		
			}
	
			resultCode = new TradeChangePasswordResult(hasSent, statusCode,
					brokerMsg, usrMsg);
	
			return resultCode;
		}
	}
}
